<?php
namespace app\admin\command;

use app\common\model\GoodsOrderModel;
use app\common\model\StoreModel;
use common\util\ArrayUtil;
use think\Log;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\console\input\Argument;

class Export extends Command {

    protected function configure() {
        $this->setName('export')
            ->setDescription('导出')
            ->addArgument('store_ids', Argument::OPTIONAL, '货仓id列表,(逗号分割)');
    }

    protected function execute(Input $input, Output $output) {
        $output->writeln('导出给物流');
       
        $emails = [
            [
                'email' => '170768429@qq.com',
                'name' => '王金喜'
            ]
        ];
        if (ENVIRONMENT == 'production') {
            $emails = [
                [
                    'email' => '170768429@qq.com',
                    'name' => '王金喜'
                ],
                [
                    'email' => 'xingfu.baobao9812@icloud.com',
                    'name' => 'xingfu'
                ],
                [
                    'email' => '2457677350@qq.com',
                    'name' => '2457677350'
                ]
            ];
        }

        $storeIds = $input->getArgument('store_ids');
        $date = date('Y-m-d');
        $where = [];
        if ($storeIds) {
            $where['id'] = [
                'in',
                $storeIds
            ];
        }
        $storeMap = StoreModel::instance()->where($where)->column('name', 'id');

        $files = [];
        try {
            foreach ($storeMap as $id => $name) {
                $name = $this->_getName($name);
                $res = $this->export_express($id, $name);
                $res && $files[] = [
                    'path' => $this->_getOrderFilePath($name),
                    'name' => $name
                ];
            }

            $title = '';
            if(ENVIRONMENT != 'production'){
                $title = ENVIRONMENT;
            }
            foreach ($emails as $item) {
                $res = send_mail($item['email'], $item['name'], "$date 快递邮寄导出", "订单文件 $title", $files);
                // $output->writeln($res);
            }
        } catch (\Exception $e) {
            Log::write('导出失败,msg:' . $e->getMessage(), Log::ERROR);
        }
        $output->writeln('导出成功');
    }

    private function export_express($storeId, $name) {
        $hour = date('H');
        $h = $hour - 2; // 提前两小时的订单
        $file = $this->_getOrderFilePath($name);
        if (file_exists($file) && false) {
            return $name;
        }
        $date = date("Y-m-d $h:00:00");
        $storeMap = StoreModel::instance()->column('name', 'id');
        $where = [];
        $where['t.ispay'] = 1;
        $where['t.store_id'] = $storeId;
        $where['t.flag'] = 0;
        $where['t.addtime'] = [
            '<=',
            $date
        ];
        $list = GoodsOrderModel::instance()->field($this->_getField())
            ->alias('t')
            ->
        // ->join('address t1', 't.receive_addr_id = t1.id', 'left')
        join('address t2', 't.send_addr_id = t2.id', 'left')
            ->where($where)
            ->order('t.id', 'desc')
            ->select();
        if ($list) {
            $ids = ArrayUtil::getKeyValuesFromArray($list, 'id');
            GoodsOrderModel::instance()->whereIn('id', $ids)->update([
                'flag' => 1
            ]);
            Log::write("export_express ids:" . implode(',', $ids));
        }
        $index = 1;
        foreach ($list as &$item) {
            $item['store'] = '';
            if ($item['store_id']) {
                $item['store'] = $storeMap[$item['store_id']];
            }
            $item['id'] = $index ++;
        }
        if (empty($list)) {
            return false;
        }
        $this->_exportExl($name, $list);
        return $name;
    }

    private function _exportExl($file, $list) {
        $excel = new \PHPExcel();
        $excel->setActiveSheetIndex(0);
        $nameValueMap = [
            'ID' => 'id',
            '订单号' => '订单号',
            '下单时间' => 'addtime',
            '产品名称' => '产品名称',
            '数量' => '数量',
            '收货人姓名' => '收货人姓名',
            '收货人电话' => '收货人电话',
            '收货人地址' => '收货人地址',
            '发货人' => '发货人',
            '发货人电话' => '发货人电话',
            '发货人地址' => '发货人地址',
            '备注' => '备注',
            '快递公司' => '快递公司',
            '快递单号' => '快递单号',
            '仓库' => 'store'
        ];

        $sums = [];
        $index = 0;
        $nameKeys = array_keys($nameValueMap);
        foreach ($nameKeys as $nameKey) {
            $excel->getActiveSheet()->setCellValue(chr($index + 65) . '1', $nameKey, \PHPExcel_Cell_DataType::TYPE_STRING2); //
            $index ++;
        }
        $valueKeys = array_values($nameValueMap);

        $j = 2;
        foreach ($list as $k => $v) {
            $index = 0;
            foreach ($valueKeys as $valueKey) {
                if (is_string($v[$valueKey])) {
                    $excel->getActiveSheet()->setCellValueExplicit(chr($index + 65) . $j, $v[$valueKey], \PHPExcel_Cell_DataType::TYPE_STRING);
                } else {
                    $excel->getActiveSheet()->setCellValue(chr($index + 65) . $j, $v[$valueKey]);
                }

                if (array_key_exists($valueKey, $sums)) {
                    $sums[$valueKey]['sum'] += $v[$valueKey];
                    if ($sums[$valueKey]['index'] == - 1) {
                        $sums[$valueKey]['index'] = $index;
                    }
                }
                $index ++;
            }
            $j ++;
        }
        foreach ($sums as $key => $value) {
            $excel->getActiveSheet()->setCellValue(chr($value['index'] + 65) . $j, $value['sum']);
        }

        $objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
        $objWriter->save($this->_getOrderFilePath($file));
    }

    private function _getName($name) {
        $h = date('H');
        $s = '';
        if($h > 18){
            $s = '晚';
        }
        return date('md') . ' ' . $name . '仓 '.$s.'.xlsx';
    }

    private function _getOrderFilePath($file) {
        return '/tmp/' . $file;
    }

    private function _getField() {
        return "t.id,t.addtime,t.oid as '订单号',concat(goodsname,' ',key_name) as '产品名称',courier_num '数量',total '金额',
                t.receive_name '收货人姓名',t.receive_tel '收货人电话',concat(t.receive_addrvalue,t.receive_addr) '收货人地址',
                IFNULL(t2.name,'') '发货人',IFNULL(t2.tel,'') '发货人电话',IFNULL(concat(t2.addrvalue,t2.addr),'') '发货人地址',
                beizhu '备注',express_name '快递公司',express_no '快递单号',t.store_id";
    }
}